package com.oocl.messagelistener;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.SocketException;

import org.json.JSONException;
import org.json.JSONObject;

import com.oocl.chatroom.network.protocol.Message;
import com.oocl.dao.impl.UserDaoImpl;
import com.oocl.message.handler.MsgHandler;
import com.oocl.service.UserService;
import com.oocl.service.impl.UserServiceImpl;

public class MsgListener implements Runnable{

	private Socket socket;
	private BufferedReader in;
	private MsgHandler handler;
	private UserService uservice;
	
	public MsgListener(Socket socket) {
		super();
		this.socket = socket;
		handler=new MsgHandler(socket);
		uservice=new UserServiceImpl();
		uservice.setUserDao(new UserDaoImpl());
		try {
			this.in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}


	public void run() {
		// TODO Auto-generated method stub
		while(socket.isConnected()){
			Message msg=null;
			//handler=new MsgHandler(socket);
			try {
				String jmsg=in.readLine();
				System.out.println(jmsg);//
				msg=changeToMessage(jmsg);
				String[] parts=msg.getContent().split(";");
				switch(msg.getType()){
				case 5:
					handler.lgNotify(parts[0], parts[1]);
					break;
				case 6:
					//System.out.println(parts[0]+"\t"+parts[1]);
					//System.out.println(handler);
					handler.regNotify(parts[0], parts[1]);
					break;
				}
			} 
			catch (SocketException e) {
				break;
			}catch (IOException e) {
				break;
			}
			
		}
	}
	
	private Message changeToMessage(String json) {
		Message msg = new Message();
		 System.out.println(json);
		try {
			JSONObject jOb = new JSONObject(json);
			System.out.println(jOb.getInt("type"));
			msg.setContent( jOb.getString("content"));
			msg.setDate(jOb.getLong("date"));
			msg.setSender( jOb.getString("sender"));
			msg.setReceiver(jOb.getString("receiver"));
			msg.setType(Integer.parseInt(jOb.getString("type")));
		}catch (JSONException e) {
			e.printStackTrace();
		}

		return msg;
	}

}
